﻿using SpreadSheetViewer.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SpreadSheetViewer.Service
{
    public class ServerFileController : Controller
    {
        // GET: ServerFileService
        public JsonResult GetReportTemplates()
        {
            IList<BaseNode> nodes = new List<BaseNode>();
            BuildMenu(SpreadSheetViewer.Helper.DirectoryManagmentUtils.CurrentDataDirectory, true, nodes);
            //return res;
            return Json(nodes, JsonRequestBehavior.AllowGet);
        }
        bool BuildMenu(string path, bool isTop, /*System.Text.StringBuilder sb, */IList<BaseNode> nodes = null)
        {
            if (nodes == null || !System.IO.Directory.Exists(path))
                return false;
            foreach (var file in System.IO.Directory.GetFiles(path))
            {
                var fileName = System.IO.Path.GetFileNameWithoutExtension(file);
                var filePath = file.Replace(SpreadSheetViewer.Helper.DirectoryManagmentUtils.CurrentDataDirectory, "");
                nodes.Add(new FileNode() { Text = fileName, Location = filePath });
            }
            foreach (var dic in System.IO.Directory.GetDirectories(path))
            {
                string fileName = dic.Replace(path, "").Replace("/", "").Replace("\\", "");
                DirectoryNode directoryNode = new DirectoryNode() { Text = fileName };
                nodes.Add(directoryNode);
                if (!BuildMenu(dic, false, directoryNode.Nodes))
                {
                    return false;
                }
            }
            return true;
        }
    }
}